#include <Windows.h>
#include <tchar.h>
#include "resource.h"

int CALLBACK DlgProc(HWND hDlg, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
	switch (nMsg)
	{
		case WM_INITDIALOG:
		{
			SetWindowText(hDlg, _T("Demo0072"));

			UINT nWidth		= GetSystemMetrics(SM_CXSCREEN);
			UINT nHeight	= GetSystemMetrics(SM_CYSCREEN);
			RECT rtClient;
			GetClientRect(hDlg, &rtClient);
			SetWindowPos(hDlg, NULL, (nWidth - (rtClient.right - rtClient.left)) / 2, (nHeight - (rtClient.bottom - rtClient.top)) / 2, 0, 0, SWP_NOSIZE);
			
			break;
		}
		case WM_COMMAND:
		{
			switch (LOWORD(wParam))
			{
				case IDC_BTNBROWSE:
				{
 					TCHAR szFilePath[MAX_PATH] = {0};
					OPENFILENAME ofn	= {0};
					ofn.lStructSize		= sizeof(ofn);
					ofn.Flags			= OFN_EXPLORER;
					ofn.hwndOwner		= hDlg;
					ofn.lpstrFile		= szFilePath;
					ofn.lpstrFileTitle	= _T("Open File");
					ofn.nMaxFile		= MAX_PATH;
					ofn.lpstrFilter		= _T("Execute file(*.exe)\0*.exe\0");
					if (GetOpenFileName(&ofn))
					{
						SetWindowText(GetDlgItem(hDlg, IDC_STCPATH), szFilePath);
					}

					break;
				}
				case IDC_BTNLAUNCH:
				case IDC_BTNLAUNCH2:
				{
					TCHAR szFilePath[MAX_PATH];
					GetWindowText(GetDlgItem(hDlg, IDC_STCPATH), szFilePath, MAX_PATH);
					if (-1 != GetFileAttributes(szFilePath))
					{
						if (LOWORD(wParam) == IDC_BTNLAUNCH)
						{
							ShellExecute(hDlg, _T("open"), szFilePath, NULL, NULL, SW_SHOWNORMAL);
						} else {
							PROCESS_INFORMATION pi	= {0};
							STARTUPINFO si			= {0};
							CreateProcess(szFilePath, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
							CloseHandle(pi.hThread);
							CloseHandle(pi.hProcess);
						}
					}

					break;
				}
			}
			break;
		}
		case WM_CLOSE:
		{
			PostQuitMessage(0);
			break;
		}
	}

	return 0;
}

BOOL WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPreInstance, LPTSTR szCmdLine, int nShowCmd)
{
	DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), NULL, DlgProc);

	return TRUE;
}
